<?php
$allRoles = $this->allRoles;
$allTemplates = $this->allTemplates;
$baseUrl = $this->serverUrl().'/';
$treeData = $this->treeData;
?>



<div class="ad_title_ctn">
    <h2>Thêm trang</h2>
</div>

<div class="ad_content_ctn">
    <div class="pa_top_ctr_ctn">
        <a id="lnkSavePageTop" class="k-button k-button-icontext" >Lưu trang</a>&nbsp;&nbsp;&nbsp;

    </div>
    <div id="pa_tabStrip">
<!--        <ul>-->
<!--            <li class="k-state-active">Thông tin page</li>-->
<!--            <li>Block page</li>-->
<!--        </ul>-->
        <div class="pa_content_ctn" id="page_info_ctn">
            <fieldset>
                <legend>Thông tin cơ bản</legend>
                <table cellspacing=10px class="pa_table_layout">
                    <tr>
                        <td class="title">Template</td>
                        <td><select id="cboTemplate" >
                            <?php
                            foreach ($allTemplates as $aTemplate) {
                                echo '<option value="'.$aTemplate->id.'">'.$aTemplate->name.'</option>';
                            }

                            ?>
                        </select></td>
                    </tr>
                    <tr>
                        <td class="title">Tên page(*):</td>
                        <td>
                            <input id="txtName" name="txtName" style="width:400px" placeholder="Nhập tên page, bắt buộc" class="k-textbox" required validationMessage="Chưa nhập tên page">
                            <span class="k-invalid-msg" data-for="txtName"></span>
                        </td>
                    </tr>
                    <tr>
                        <td class="title">Tiêu đề(*):</td>
                        <td>
                            <input id="txtTitle" name="txtTitle" style="width:400px" placeholder="Nhập tiêu đề, bắt buộc" class="k-textbox" required validationMessage="Chưa nhập tiêu đề">
                            <span class="k-invalid-msg" data-for="txtTitle"></span>
                        </td>
                    </tr>
                    <tr>
                        <td class="title">Description:</td>
                        <td>
                            <input id="txtDescription" name="txtDescription" style="width:500px" placeholder="Nhập mô tả" class="k-textbox" >
                        </td>
                    </tr>
                    <tr>
                        <td class="title">URL:</td>
                        <td>

                            <input id="txtUrl" name="txtUrl" style="width:400px" placeholder="Nhập url page" class="k-textbox" >
                            &nbsp; &nbsp;&nbsp;<a  href="<?php echo $baseUrl ?>" id="lnkBaseUrl"><?php echo $baseUrl ?></a>
                            <br>
                            <div class="parameter_def_box" style="display: none">

                            </div>

                        </td>
                    </tr>
                </table>
            </fieldset>

            <fieldset>
                <legend>Thông tin module-controller-action</legend>
                <table cellspacing=10px class="pa_table_layout">
                    <tr>
                        <td class="title">
                            Module
                        </td>
                        <td>
                            <select id="cboModule">
                                <?php
                                $allModules = \Core\Helper\ApplicationDirectoryHelper::getAllModuleForAdmin();
                                foreach ($allModules as $aModule) {
                                    echo '  <option value="'.$aModule.'">'.$aModule.'</option>';
                                }

                                ?>
                            </select>
                        </td>

                    </tr>
                    <tr>
                        <td class="title">
                            Controller
                        </td>
                        <td>
                            <select id="cboController">
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td class="title">Action (*):</td>
                        <td>
                            <input id="txtAction" name="txtAction" style="width:200px" placeholder="Nhập action, bắt buộc" class="k-textbox" required validationMessage="Chưa nhập action">
                            <span class="k-invalid-msg" data-for="txtAction"></span>
                        </td>
                    </tr>

                    <tr>
                        <td colspan="2">
                            <div id="pageEditContainer">
                                <a href="javascript:openPageAdd();"><i class="fa fa-eye"></i>&nbsp;Sửa mẫu</a>
                            </div>
                        </td>

                    </tr>
                </table>

            </fieldset>

            <fieldset>
                <legend>Phân quyền truy cập</legend>
                <table cellspacing=10px class="pa_table_layout">
                    <tr>
                        <td class="title">
                            Mã quyền
                        </td>
                        <td>
                            <input id="txtPrivilege" style="width:400px;" disabled="disabled" class="k-textbox" >
                        </td>

                    </tr>
                    <tr>
                        <td colspan="2">
                            <span style="font-weight: bold">Cho phép tất cả truy cập:<span> <input type="checkbox" name="chkPublishToAll" id="chkPublishToAll" checked="checked">
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <p style="font-weight: bold">Gán cho nhóm</p>
                            <div style="padding: 5px; ">
                                <input type="checkbox" name="chkAllRole" id="chkAllRole" class="checkAll" >All<br>
                                <?php

                                foreach ($allRoles as $roleItem) {
                                    echo '<input   type="checkbox" name="chkRole" value="'.$roleItem->id.'" /> '.$roleItem->name.'<br />';
                                }
                                ?>
                            </div>
                        </td>
                    </tr>
                </table>

            </fieldset>
        </div>
    </div>
    <div class="pa_bottom_ctr_ctn">
        <a id="lnkSavePageBottom" class="k-button k-button-icontext">Lưu trang</a>&nbsp;&nbsp;&nbsp;

    </div>
</div>


<script type="text/javascript">
    <?php echo 'var baseUrl="'.$baseUrl.'";' ?>
    var validator;
    $(document).ready(function(){


        $('#txtPrivilege').val(USER_DEF_PRIVILEGE_PREFIX + USER_DEF_DEFAULT_PRIVILEGE +USER_DEF_PRIVILEGE_SURFIX);
        validator = $("#page_info_ctn").kendoValidator().data("kendoValidator");

        $("#cboModule").kendoComboBox({
            filter: "contains",
            suggest: true,
            index: 3,
            change: function(e) {
                loadController();
                blockMap = [];
            }
        });

        var cboModule = $("#cboModule").data("kendoComboBox");

        $("#cboController").kendoComboBox();
        var cboController = $("#cboController").data("kendoComboBox");

        $("#cboTemplate").kendoComboBox();
        var cboTemplate = $("#cboTemplate").data("kendoComboBox");

        $("#txtAction").change(function(){
            blockMap = [];
        })


        function loadController(){
            selectedModule = cboModule.value();
            $.post('/admin/common/get-controller-by-module',{mymodule:selectedModule}
                    ,function(result){
                        if (result.success){
                            data = result.data;
                            cboController.setDataSource(data)
                            blockMap = []
                        }else{
                            alert(result.msg)
                        }

                    },'json');
        }
        loadController();

        function validate(){

            return validator.validate();
        }

        function savePage(){
            if(!validate())
            return;
            name = $("#txtName").val();
            title = $("#txtTitle").val();
            description = $("#txtDescription").val();
            route = $.vietnameseToASCII($("#txtUrl").val().toLowerCase());
            privilegeCode = $("#txtPrivilege").val();
            accessRoles = [];
            $(":input[name='chkRole']").each(function() {
                if($(this).is(':checked'))
                    accessRoles.push(this.value);
            });

            isPublishToAll = $("#chkPublishToAll").is(":checked")?1:0;

            templateId = $("#cboTemplate").val();
            myModule = cboModule.value()
            myController = cboController.value()
            myAction = $("#txtAction").val();


            tmpArr =  [];
            for (var obj in blockMap) {
                tmpArr.push(obj+"$$$"+blockMap[obj]);
            }

            paraDefArr = [];
            $('.a_param_chooser').each(function(){
                paramName = $(this).find('span').text();
                paramDef = $(this).find('select.cboUrlParam').val();
                paraDefArr.push(paramName +"$$$"+ paramDef);
            })


            $.post('/admin/page/save-page',{
                name:name, title:title, description:description,
                route:route, privilegeCode:privilegeCode,accessRoles:accessRoles,
                blockInstanceIds:tmpArr,isPublishToAll:isPublishToAll,myModule:myModule,
                templateId:templateId,myController:myController,paraDefs:paraDefArr,
                myAction:myAction
            },function(result){
                if (result.success){
                    pageId = result.pageId;


                    window.location="/admin/page";
                }
                else{
                    $('#error_ctn').html(result.msg);
                    alert(result.msg);
                }
            },'json');
        }

        $('#lnkSavePageTop').click(function(){
            savePage();
        })
        $('#lnkSavePageBottom').click(function(){
            savePage();
        })





    });

    $("#chkPublishToAll").change(function(){
        if($(this).is(':checked')){
            $(":input[name='chkRole']").removeAttr("checked");
            $(":input[name='chkAllRole']").removeAttr("checked");
        }else{
            $(":input[name='chkRole']").attr("checked", true);
            $(":input[name='chkAllRole']").attr("checked", true);
        }
    })

    $(":input[name='chkRole']").change(function(){
        if($(this).is(':checked')){
            $("#chkPublishToAll").removeAttr("checked");
        }else{

            isHavingRoleCheck = false;
            $(":input[name='chkRole']").each(function(){
                if($(this).is(':checked')) isHavingRoleCheck = true;
            })
            if(!isHavingRoleCheck) $("#chkPublishToAll").attr("checked", true);
            $(":input[name='chkAllRole']").removeAttr("checked");

        }
    })

    $(":input[name='chkAllRole']").change(function(){
        if($(this).is(':checked')){
            $("#chkPublishToAll").removeAttr("checked");
            $(":input[name='chkRole']").each(function(){
                $(this).attr("checked", true)
            })
        }else{
            $("#chkPublishToAll").attr("checked", true);
            $(":input[name='chkRole']").each(function(){
                $(this).attr("checked", false)
            })

        }
    })

    $("#txtUrl").keyup( function(event) {
        event.preventDefault();
        decorateUrl();
    });
    function decorateUrl(){
        val = $("#txtUrl").val();
        val = $.vietnameseToASCII(val);
        url = baseUrl+ val.toLowerCase();
        $("#lnkBaseUrl").attr("href", url);
        $("#lnkBaseUrl").text(url);
    }
    $("#txtUrl").blur(function() {
        //check if route exists
        route = $("#txtUrl").val();

        $.post('/admin/page/check-route-exists',{route:route},function(result){
            if (result.success){
                if(result.exists){
                    alert('Url đã tồn tại');
                    $('#error_ctn').removeClass('blue_text').html('Url đã tồn tại');
                    $("#txtUrl").focus();
                    $("#txtUrl").select();
                }
                else{
                    val = $("#txtUrl").val();

                    val = val.replace(/\/:/gi,"$");
                    val = val.replace(/\//gi,"_");
                    val = val.replace(/-/gi,"_");
                    val = $.vietnameseToASCII(val);
                    val = val.toUpperCase();

                    if(!val || val == '')
                        val = USER_DEF_DEFAULT_PRIVILEGE;
                    $("#txtPrivilege").val(USER_DEF_PRIVILEGE_PREFIX + val +USER_DEF_PRIVILEGE_SURFIX);
                    $(":input[name='chkRole']").removeAttr("disabled");
                    $(":input[name='chkAllRole']").removeAttr("disabled");
                    $("#chkPublishToAll").removeAttr("disabled");
                    showParameterChooseBox($("#txtUrl").val());
                }

            }else{
                alert(result.msg)
                $('#error_ctn').removeClass('blue_text').html(result.msg);
            }

        },'json');
    });

    function showParameterChooseBox(url){
        $.post('/admin/page/get-parameter-box',{url:url},function(result){
            if($.trim(result).length > 0){
                $('.parameter_def_box').show();
                $('.parameter_def_box').html(result);
            }else{
                $('.parameter_def_box').hide();
            }
        });
    }



    function openPageAdd(){
        templateId = $("#cboTemplate").val();
        module = $("#cboModule").val();
        controller = $("#cboController").val();
        action = $("#txtAction").val();
        if(!action) {
            alert('Nhập dữ liệu module, controller, action để load mẫu trang.')
            return;
        }
        url = '/admin/page/edit-page?templateId='+templateId + '&mymodule='+module+ '&mycontroller='+controller+ '&myaction='+action;
        win=window.open(url, '_blank');
        win.focus();
    }

    var blockMap = [];

</script>
